package a1_p04_ak_fh;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.swing.JFrame;
import javax.swing.DefaultDesktopManager;

import org.jgraph.graph.DefaultEdge;
import org.jgrapht.DirectedGraph;
import org.jgrapht.Graph;
import org.jgrapht.graph.DefaultDirectedGraph;
import org.jgrapht.graph.SimpleGraph;

import com.mxgraph.swing.mxGraphComponent;
import com.mxgraph.view.mxGraph;


public class GraphVis extends JFrame {

	private GraphVis(Graph g,Integer o)
	{

		int i = 1,x = 1;
		int y = 1;
		
		mxGraph graph = new mxGraph();
		Object parent = graph.getDefaultParent();
		Set<Object> cedges = null;
		HashMap<String,Object> visitedvertex = new HashMap<String,Object>();
		

		graph.getModel().beginUpdate();

		Set<DefaultEdge> edges = g.edgeSet();
		String order = "";
		// Style informations
		if(o==1){
			order="startArrow=none;endArrow=none;strokeWidth=4;strokeColor=#F00F00";
		}else{
			order="strokeWidth=4;strokeColor=#66FF00";
		}
		try
		{
			
			// Going to each edge of the graph
			for (DefaultEdge e : edges) {
				// Source already visited?
				if(!visitedvertex.containsKey(g.getEdgeSource(e).toString())){
					// put source to visited vertex list and add the vertex to the visualisation
					visitedvertex.put(g.getEdgeSource(e).toString(), graph.insertVertex(parent, null, g.getEdgeSource(e), i*100, y*100, 40,20));
				}
				// Target already visited?
				if (!visitedvertex.containsKey(g.getEdgeTarget(e).toString())){
					// put target to visited vertex list and add the vertex to the visualisation
					visitedvertex.put(g.getEdgeTarget(e).toString(),graph.insertVertex(parent, null, g.getEdgeTarget(e), i*200, y*200, 40,20));
				}
				// Add the edge to the visualisation
				graph.insertEdge(parent, null, "Edge "+x, visitedvertex.get(g.getEdgeSource(e)), visitedvertex.get(g.getEdgeTarget(e)),order);
				if(i==6){
					i=1;
					y++;
				}
				i++;
				x++;
			}
		}
		finally
		{
			graph.getModel().endUpdate();
		}

		mxGraphComponent graphComponent = new mxGraphComponent(graph);
		getContentPane().add(graphComponent);
		
	}
	
	/**
	 * factory methods
	 * @param graph : Graph/home/fabian/EclipseWorkspace/gka_wise12
	 * @param i : 1 for undirected graph else directed
	 */
	public static void startvis(Graph graph, Integer i)
	{
		GraphVis frame = new GraphVis(graph,i);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(400, 320);		
		frame.setVisible(true);		
	}
}
